(function(Test){
	var Base = ideon.module("base");
	Test.Model.Message = Base.Model.BaseModel.extend({
	// MODELS
		defaults: {
			title:					"",
			content:			"",
		},
	});
	
	// COLLECTIONS
	Test.Collection.Messages = Base.Collection.Paginated.extend({	
		model:	Test.Model.Message,
		url: "http://localhost:9000/backbone/messages",
	});
	
	// VIEWS
	Test.View.Item = Base.View.Item.extend({
		template: _.template($("#item-template").html()),
	});
	
	Test.View.ListView = Backbone.View.extend({
		_itemView:	Test.View.Item,
		
		template: _.template($("#list-template").html()),
		
		events: {
			"click a.page":		"changePage",
		},

			
		initialize: function(options) {
			this.router = options.router;
			this.collection.bind("reset", this.render, this);
		},
		
		render: function() {
			this.renderList();
			
			return this;
		},
		
		renderList: function() {
			// Build pagination and the body template
			$(this.el).html(this.template({pagination: this.collection.pageInfo()}));
			var self = this;
			
			// Build the list
			var $list = this.$(".list");
			
			this.collection.each(function(item){
				var itemView = new self._itemView({
					model:	item
				});
				console.log(itemView.render().el);
				$list.append(itemView.render().el);
			});
		},
		
		changePage: function(e) {
			console.log("Change page");
			e.preventDefault();
			var page = $(e.currentTarget).data("id") ? $(e.currentTarget).data("id") : 1;
			var start = (page-1) * this.collection.limit;
			this.collection.offset = start;
			this.collection.fetch();
			//this.router.navigate("#page"+page);
		},
	});
	// This view has to be used with the List view.
		
	Test.View.App = Base.View.App.extend({});
	
	// Router
	Test.Router.App = Backbone.Router.extend({
		routes: {
			"":						"index",
		},
		
		initialize: function() {
			this.appView = new Test.View.App();
		},
		
		index: function() {
			var messages = new Test.Collection.Messages([], {paginated: true});
			
			messages.fetch();
			var messagesListView = new Test.View.ListView({
				collection: messages,
				router: this,
			});
			$(this.appView.el).html(messagesListView.render().el);
		},
	});
})(ideon.module("ideonTest"));
